package com.example.demo.controller;

import cn.hutool.core.lang.WeightRandom;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.example.demo.pojo.JsonResult;
import com.example.demo.pojo.Prize;
import com.example.demo.pojo.User;
import com.example.demo.pojo.security.UserSecurity;
import com.example.demo.service.PrizeService;

import com.example.demo.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class PrizeController {
    @Resource
    private PrizeService prizeService;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate st;
    private static String key="redis";
    @PostMapping("/query")
    public JsonResult query(){
        List<Prize> list = prizeService.list();
        ArrayList<JSONObject> list1 = new ArrayList<>();

        list.stream().forEach(k->list1.add(JSONUtil.parseObj(k.getName())));
        return new JsonResult(list1);
    }
    @PostMapping("/prize")
    public JsonResult prize(){
        try{
            Boolean lock = st.opsForValue().setIfAbsent(key, " 锁");
            UserSecurity userSecurity = (UserSecurity) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            User user = userSecurity.getUser();
            if (lock){
                if (user.getFrequency()<=0){
                    throw new Exception();
                }
                List<Prize> prizes = prizeService.list(null);
                prizes=prizes.stream().filter(k->k.getNumber()>0).collect(Collectors.toList());
                if (prizes.size()==0){
                    List<Prize> list = prizeService.list(null);
                    for (int i = 0; i < list.size(); i++) {
                        Prize prize = list.get(i);
                        String name = prize.getName();
                        JSONObject jsonObject = JSONUtil.parseObj(name);
                        String str = jsonObject.getJSONArray("fonts").getJSONObject(0).getStr("text");
                        if (str.contains("遗憾")){
                            user.setPrize(str);
                            user.setFrequency((user.getFrequency()-1));
                            userService.updateById(userSecurity.getUser());
                            prizeService.updateById(prize);
                            return new JsonResult(i);
                        }
                    }
                }
                double sum = prizes.stream().filter(k -> k.getNumber() > 0).mapToDouble(k -> k.getProbability()).sum();
                List<WeightRandom.WeightObj<Prize>> weightObjs = new ArrayList<>();
                prizes.forEach(award -> {
                    weightObjs.add(new WeightRandom.WeightObj<>(award, award.getProbability()));
                });
                WeightRandom random = RandomUtil.weightRandom(weightObjs);
                Prize prize = (Prize) random.next();
                Integer number = prize.getNumber();
                prize.setNumber(--number);
                String name = prize.getName();
                JSONObject jsonObject = JSONUtil.parseObj(name);
                String str = jsonObject.getJSONArray("fonts").getJSONObject(0).getStr("text");
                user.setPrize(str);
                user.setFrequency((user.getFrequency()-1));
                userService.updateById(userSecurity.getUser());
                prizeService.updateById(prize);
                List<Prize> list = prizeService.list(null);
                int index=0;
                for (int i = 0; i < list.size(); i++) {
                    Prize prize1 = list.get(i);
                    if (prize1.getId()==prize.getId()){
                        index=i;
                    }
                }
                st.delete(key);
                return new JsonResult(index);

            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            st.delete(key);
        }
        List<Prize> list = prizeService.list(null);
        int index=0;
        for (int i = 0; i < list.size(); i++) {
            Prize prize = list.get(i);
            String name = prize.getName();
            JSONObject jsonObject = JSONUtil.parseObj(name);
            String str = jsonObject.getJSONArray("fonts").getJSONObject(0).getStr("text");
            if (str.contains("遗憾")){
                index=i;
            }
        }

        return new JsonResult(index);
    }
}
